package cn.hd.service.impl;

import cn.hd.dao.PowerDao;
import cn.hd.dao.RoleDao;
import cn.hd.dao.UserDao;
import cn.hd.entity.Power;
import cn.hd.entity.Role;
import cn.hd.entity.User;
import cn.hd.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PowerDao powerDao;
    @Autowired
    private UserDao userDao;
    public PageInfo<Role> selectAll(int pageNum) {
        int pageSize = 2;
        PageHelper.startPage(pageNum,pageSize);
        List<Role> list = roleDao.selectAll();
        PageInfo<Role> page = new PageInfo<>(list);
        return page;
    }

    @Override
    public PageInfo<Role> selectAllBN(int pagenum,int pagsesize,Map map) {
        PageHelper.startPage(pagenum,pagsesize);
        List<Role> roles = roleDao.selectAllBN(map);
        //以业务逻辑的形式，从数据库中把当前角色所属的二级菜单查询到放入到对应的一级菜单中
        System.out.println(roles.toString());
        for(int i = 0;i <roles.size();i++){
            Role role = roles.get(i);//给一个对象

            for(int j = 0;j < role.getChildren().size();j++){//遍历所有的一级菜单
                Power p = role.getChildren().get(j);//每一个一级菜单
                //根据其一级菜单编号和角色编号，来查询二级菜单集合
                //role.getRoleId()得到角色id,p.getId角色下的二级权限的id
                List<Power> powers = powerDao.selectTwoPowerByRidAndPid(role.getRoleId(), p.getId());
                p.setChildren(powers);
                System.out.println(p.getChildren().toString());
            }
        }
        PageInfo<Role> page = new PageInfo<>(roles);
        return page;
    }

    @Override
    public List<Role> selectRole() {
        return roleDao.selectAll();
    }

    @Override
    public int addRole(Role role) {
        return roleDao.addRole(role);
    }

    @Override
    public int deleteRole(long roleId) {
        return roleDao.deleteRole(roleId);
    }

    @Override
    public int updateRole(Role role) {
        return roleDao.updateRole(role);
    }

    @Override
    public Role selectByRid(long rid) {
        return roleDao.selectByRid(rid);
    }

    @Override
    public int deleteRolePower(long rid) {
        return roleDao.deleteRolePower(rid);
    }

    @Override
    public int insertRolePower(long rid, long pid) {
        return roleDao.insertRolePower(rid,pid);
    }

    @Override
    public PageInfo<User> selectUsersByRoleId(int pagenum, int pagesize, long id) {
        PageHelper.startPage(pagenum,pagesize);
        List<User> users = roleDao.selectUsersByRoleId(id);
        for (User s : users) {
            String roleName = userDao.selectRoleById(s.getId());
            s.setJs(roleName);
        }
        PageInfo<User> page = new PageInfo<>(users);
        return page;
    }
}
